import config from "@/request/config.js";
// 本地存储名称
const localStorageNames = ["userInfo", "token", "shareId", "location", "appConfig", "pageId", "school"];

export const state = {
    scene: null, // 小程序场景值
    token: null, // Token
    logid: null, // 日志ID
    pageId: null, // 页面ID
    loading: false, // 是否显示加载中
    shareId: null, // 分享ID
    location: {}, // 定位信息
    appConfig: {}, // app配置相关数据
    baseUrl: null, // 基础接口地址
    devPosition: {
        x: 0,
        y: 200
    }, // 开发环境组件位置信息
    school: null,
};

export const mutations = {
    // 初始化
    initApp(state, options) {
        localStorageNames.forEach(name => {
            let data = uni.getStorageSync(name);
            if (data) state[name] = data;
        });
        // 设置基础接口地址
        state.baseUrl = config.baseUrl;

        // #ifdef MP-WEIXIN
        // 小程序平台获取场景值
        if (options && options.scene) {
            state.scene = options.scene;
        }
        // 小程序平台获取分享ID
        if (options && options.query.shareId) {
            state.shareId = options.query.shareId;
            mutations.setState(state, {
                name: 'shareId',
                data: options.query.shareId
            });
        }
        // #endif
    },
    // 关闭app
    closeApp(state) {
        state.token = null;
        state.userInfo = {};
        uni.clearStorageSync();
    },
    // 设置token
    setToken(state, data) {
        state.token = data;
        uni.setStorageSync('token', data);
    },
    // 设置状态
    setState(state, data) {
        // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
        let nameArr = data.name.split('.');
        let name = '';
        let len = nameArr.length;
        if (nameArr.length >= 2) {
            let obj = state[nameArr[0]];
            for (let i = 1; i < len - 1; i++) {
                obj = obj[nameArr[i]];
            }
            obj[nameArr[len - 1]] = data.data;
            name = nameArr[0];
        } else {
            // 单层级变量，在state就是一个普通变量的情况
            state[data.name] = data.data;
            name = data.name;
        }
        if (localStorageNames.includes(name)) {
            uni.setStorageSync(name, state[name]);
        }
    },
    // 设置token
    setSchool(state, data) {
        state.school = data;
        uni.setStorageSync('school', data);
    },
};

export const actions = {

};